<?php

declare(strict_types=1);

namespace App\Controller\Rpc;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;

/**
 * redis 无锁并发优化
 * @Controller(prefix="/Rpc/Concurrency")
 */
class ConcurrencyController extends AbstractController
{
    var $number_key = '1000111';
    
    /**
     * @RequestMapping(path="decre",method="GET")
     */
    public function decreNumber(RequestInterface $request)
    {
        $redis = redis();
        $decre_result = $redis->decr($this->number_key,1);
        if( $decre_result > 0 ) {
            echo "扣减成功:{$decre_result}\r\n";
            //做业务代码处理
            return $decre_result;
        }

        //开启事务机制
        $redis->multi();
        $redis->set($this->number_key,"0");
        //改变bit占位,00000000，第一位必须要为0，如果为1的情况下，无法在写入值
        $redis->setBit($this->number_key,0,true);
        $redis->exec();
        echo "开始执行redis bit set func:{$decre_result}\r\n";
        
        /* try {
            //开启事务
            $redis->multi();
            $redis->set($this->number_key,"0");
            $redis->setBit($this->number_key,0,true);
            $redis->exec();
            echo "开始执行redis bit set func:{$decre_result}\r\n";
        } catch ( \Throwable $th) {
            echo "系统开始抛出异常，扣减失败:{$th->getMessage()}\r\n";
        } */
        
        return $decre_result;
    }
    
    /**
     * @RequestMapping(path="flushIncrNumber",method="GET")
     * RateLimit(create=1, capacity=1)
     * Cacheable(prefix="xiaochen",ttl=5,value="_#{id}")
     */
    public function flushIncrNumber(RequestInterface $request)
    {
        $redis = redis();
        $redis->set($this->number_key,2);
        return "ok";
    }
}